/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

// 网点公众号管理

import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { getAccountsList } from '@/services/networkWx';
import { Button, Switch, Form, Input, Space } from 'antd';
import KbPopconfirm from '@/components/KbPopconfirm';
import ProForm, {
  DrawerForm,
  ProFormText,
  ProFormSelect,
  ProFormDateRangePicker,
  ProFormDateTimePicker,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { isArray } from 'lodash';
import dataParam from './types/config';
import type { Kbdby } from './index.d';
import styles from './index.less';
import { history, useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';

interface renderParam {
  label: string;
  children: [];
  map: any;
}

const Administrators: React.FC = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const formRef1 = useRef<ProFormInstance>();
  const formRef2 = useRef<ProFormInstance>();
  const formRef3 = useRef<ProFormInstance>();
  const formRef4 = useRef<ProFormInstance>();
  const secrchOption = [
    { value: 1, label: '开启' },
    { value: 0, label: '关闭' },
  ];
  const titles = { jurisdiction: '权限管理', menu: '菜单链接', b: '管理员', edit: '编辑' };

  const [options, setOptions] = useState('');
  const [drawerTitle, setDrawerTitle] = useState('');
  const [renderParam, setRenderParam] = useState([]);
  const [drawerVisit, setDrawerVisit] = useState(false);
  const [defaultUrl, setDefaultUrl] = useState('https://mt.kuaidihelp.com');
  const [currentData, setCurrentData] = useState({} as any);
  const [warrantUrl, setWarrantUrl] = useState('');
  const [searchData, setSearchData] = useState({});

  const setInitialValues = async (params: any) => {
    const callback = params.cb;
    getAccountsList(params).then((data) => {
      const { auth_cancel_time, auth_time, ...rest } = data;
      if (!auth_cancel_time) {
        rest.auth_time = auth_time;
      } else if (!auth_time) {
        rest.auth_cancel_time = auth_cancel_time;
      }
      formRef4.current?.setFieldsValue(rest);
    });
    if (typeof callback === 'function') {
      callback();
    }
    return true;
  };

  const onAuthority = (params: any, index: any) => {
    if (index === 'administrators') {
      const { platform: open_platform, platform_type } = params;
      history.push({
        pathname: '/f/wechat/official/admin',
        query: {
          open_platform,
          platform_type,
        },
      });
      return;
    }
    const action = {
      jurisdiction: 'authInfo',
      edit: 'authOfficialAccountsGet',
    };
    setCurrentData(params);
    setOptions(index);
    setRenderParam(dataParam[index]);
    setDrawerTitle(titles[index]);
    setDrawerVisit(true);
    setInitialValues({ action: action[index], platform: params.platform });
  };

  const tableReload = () => {
    const { reset } = actionRef.current || {};
    actionRef.current?.reload(false);
    if (!reset) return;
    reset();
  };

  const confirm = (values: any) => {
    setInitialValues({
      action: 'changeCloseStatus',
      platform: values.platform,
      cb: () => {
        tableReload();
      },
    });
  };

  const columns: ProColumns<Kbdby>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      search: false,
      width: 80,
      ellipsis: true,
      render: (is_franchisee, r, index) => index + 1,
    },
    {
      title: '平台标识',
      dataIndex: 'platform',
      align: 'center',
      width: 120,
      ellipsis: true,
      search: false,
    },
    {
      title: '名称',
      dataIndex: 'nick_name',
      align: 'center',
      width: 200,
      ellipsis: true,
      search: false,
    },
    {
      title: '原始ID',
      dataIndex: 'gh_id',
      align: 'center',
      width: 120,
      ellipsis: true,
      search: false,
    },
    {
      title: '用户信息',
      dataIndex: 'user_info',
      align: 'center',
      width: 120,
      ellipsis: true,
      search: false,
      render: (obj: any, r) => {
        const { user_info = {} } = r;
        const allUser = user_info.name || user_info.phone;
        return `${
          allUser
            ? `${user_info.name ? user_info.name : ''} ${user_info.phone ? user_info.phone : ''}`
            : '-'
        }`;
      },
    },
    {
      title: '加盟商（是/否）',
      dataIndex: 'is_franchisee',
      align: 'center',
      width: 120,
      ellipsis: true,
      search: false,
      render: (is_franchisee, r) => (r.is_franchisee == '1' ? '是' : '否'),
    },
    {
      title: '实属加盟商',
      dataIndex: 'franchisee_info',
      align: 'center',
      width: 200,
      ellipsis: true,
      search: false,
    },
    {
      title: '开始服务时间',
      dataIndex: 'auth_time',
      align: 'center',
      width: 200,
      ellipsis: true,
      search: false,
    },
    {
      title: '结束服务时间',
      dataIndex: 'auth_cancel_time',
      align: 'center',
      width: 200,
      ellipsis: true,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      dataIndex: 'option',
      width: winSize === 'xs' ? 100 : 200,
      align: 'center',
      fixed: 'right',
      render: (_, record: any) => (
        <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
          <a onClick={() => onAuthority(record, 'jurisdiction')}>权限管理</a>
          <a onClick={() => onAuthority(record, 'menu')}>菜单链接</a>
          <a onClick={() => onAuthority(record, 'administrators')}>管理员</a>
          <KbPopconfirm
            text={`您确定${
              record.is_close == '1' ? '开启' : record.is_close == '0' ? '关闭' : ''
            }此公众号吗？`}
            confirm={() => confirm(record)}
            cancel={() => {}}
            okText='确定'
            cancelText='取消'
            key={record.id}
          >
            <Button size='small' key='pay' type='primary' danger>
              {`${record.is_close == '1' ? '开启' : record.is_close == '0' ? '关闭' : ''}`}服务
            </Button>
          </KbPopconfirm>
          <a onClick={() => onAuthority(record, 'edit')}>编辑</a>
        </Space>
      ),
    },
  ];

  const fetchTableList = (params: any, searchData_: any) => {
    const { current: page, pageSize } = params;
    return getAccountsList({
      action: 'authOfficialAccountsList',
      page_num: page,
      page_size: pageSize,
      type: 1, // 1公众号 2小程序
      ...searchData_,
    });
  };

  const onSubmit = async (values: any = {}) => {
    if (isArray(values.search_key)) {
      const [start_time, over_time] = values.search_key;
      values = {
        ...values,
        start_time,
        over_time,
      };
      delete values.search_key;
    }
    setSearchData(values);
    tableReload();
    return true;
  };

  const onChange = (checked: boolean) => {
    if (checked) {
      setDefaultUrl('https://mt.kuaidihelp.com');
    } else {
      setDefaultUrl('https://m.kuaidihelp.com');
    }
  };

  const onSearch = (values: any, currentData_: any) => {
    getAccountsList({
      action: 'wtMenuLink',
      url: values,
      platform: currentData_.platform,
    }).then((data) => {
      if (!data) return;
      setWarrantUrl(data);
    });
  };

  const onReload = async () => {
    await formRef1.current?.resetFields();
    await formRef2.current?.resetFields();
    await formRef3.current?.resetFields();
    onSubmit();
    return true;
  };

  const { Search } = Input;
  return (
    <PageContainer className={styles.main} title=''>
      <Space direction='vertical' className={styles.space}>
        <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
          <ProForm
            formRef={formRef1}
            layout='inline'
            onFinish={onSubmit}
            submitter={{
              render: (props) => {
                return [
                  <Button type='primary' key='submit' onClick={() => props.form?.submit?.()}>
                    搜索
                  </Button>,
                ];
              },
            }}
          >
            <ProFormText name='search_key' width='md' placeholder='请输入名称/平台标识进行搜索' />
          </ProForm>
          <ProForm
            formRef={formRef2}
            layout='inline'
            onFinish={onSubmit}
            // initialValues={{
            //   search_key: [start_time, end_time]
            // }}
            submitter={{
              render: (props) => {
                return [
                  <Button type='primary' key='submit' onClick={() => props.form?.submit?.()}>
                    搜索
                  </Button>,
                ];
              },
            }}
          >
            <ProFormDateRangePicker name='search_key' width='md' />
          </ProForm>
          <ProForm
            formRef={formRef3}
            layout='inline'
            onFinish={onSubmit}
            submitter={{
              render: (submitProps) => {
                return [
                  <Button type='primary' key='submit' onClick={() => submitProps.form?.submit?.()}>
                    搜索
                  </Button>,
                ];
              },
            }}
          >
            <ProFormSelect
              options={secrchOption}
              width='md'
              name='status'
              placeholder='请选择服务状态'
            />
          </ProForm>
          <Button onClick={onReload}>重置</Button>
        </Space>
      </Space>

      <DrawerForm
        title={drawerTitle}
        visible={drawerVisit}
        formRef={formRef4}
        onVisibleChange={setDrawerVisit}
        onFinish={(values) =>
          setInitialValues({
            action: options === 'edit' ? 'authOfficialAccountsEdit' : 'editAuthInfo',
            ...values,
            platform: currentData.platform,
            cb: () => tableReload(),
          })
        }
        width={winSize === 'xs' ? 300 : options === 'menu' ? 'auto' : 800}
      >
        {renderParam.map((key: renderParam, index0: number) => {
          return (
            <div key={index0}>
              <div>
                <h2>{key.label}</h2>
                {options === 'jurisdiction' || options === 'edit' ? (
                  <ProForm.Group>
                    {key.children.map(
                      (
                        item: {
                          name: string;
                          label: string;
                          placeholder: string;
                          disabled: boolean;
                          isSelect: boolean;
                          option: any;
                          TimePicker: boolean;
                        },
                        index: number,
                      ) => {
                        return item.TimePicker ? (
                          <ProFormDateTimePicker
                            key={index}
                            name={item.name}
                            width='md'
                            label={item.label}
                          />
                        ) : item.isSelect ? (
                          <ProFormSelect
                            key={index}
                            options={item.option}
                            width='md'
                            name={item.name}
                            label={item.label}
                          />
                        ) : (
                          <ProFormText
                            key={index}
                            name={item.name}
                            width='md'
                            disabled={item.disabled}
                            label={item.label}
                            placeholder={item.placeholder || item.label}
                          />
                        );
                      },
                    )}
                  </ProForm.Group>
                ) : options === 'menu' ? (
                  <div>
                    {key.children.map(
                      (item: { label: string; defaultUrl: string }, index: number) => {
                        return (
                          <div key={index} style={styles.label}>
                            {item.label}: {defaultUrl + item.defaultUrl}
                          </div>
                        );
                      },
                    )}
                    <Form.Item label='是否线上' className={styles.FormItem}>
                      <Switch defaultChecked onChange={onChange} />
                    </Form.Item>
                    <Search
                      placeholder='请输入链接'
                      allowClear
                      enterButton='获取授权链接'
                      size='large'
                      onSearch={(values) => onSearch(values, currentData)}
                    />
                    <div>{warrantUrl}</div>
                  </div>
                ) : (
                  ''
                )}
              </div>
            </div>
          );
        })}
      </DrawerForm>
      <DragTable>
        <ProTable<Kbdby>
          className='kb-pro-table'
          actionRef={actionRef}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          rowKey='id'
          request={(values) => fetchTableList(values, searchData)}
          columns={columns}
          search={false}
          options={false}
          scroll={{ x: 1300 }}
        />
      </DragTable>
    </PageContainer>
  );
};

export default Administrators;
